#include "extqtshare.h"
#include "readdatathread.h"

#include <QCoreApplication>
#include <QString>
#include <QDebug>

QCoreApplication *qCoreApp = nullptr;


ExtQtShare::ExtQtShare()
    : m_mainThread(nullptr)
    , m_countChangedCallBack(nullptr)
{
}

bool ExtQtShare::init()
{
    if (m_mainThread) {
        qDebug() << "library main thread already created";
        return true;
    }

    m_mainThread = new std::thread([=](){
        if (QCoreApplication::instance() == nullptr) {
            int argc = 0;
            char** argv = nullptr;
            qCoreApp = new QCoreApplication(argc, argv);
        }
        //在此运行库逻辑

        ReadDataThread readThread;
        QObject::connect(&readThread, &ReadDataThread::countChanged, qCoreApp, [=](int cnt){
            qDebug() << QString().asprintf("[tid:%p] receive cnt=%d", QThread::currentThreadId(), cnt);
            if (m_countChangedCallBack) {
                m_countChangedCallBack(cnt);
            }
        }, Qt::QueuedConnection);

        readThread.start();

        qCoreApp->exec();
    });
    return true;
}

void ExtQtShare::registerCountChangedCallBack(std::function<void (int)> callback)
{
    m_countChangedCallBack = callback;
}

std::string ExtQtShare::hello()
{
    QString msg("This is the message from Qt share library!");
    return msg.toStdString();
}
